# # -*- coding: utf-8 -*-
# """
# Created by lpf on 2016/8/17 14:00:00.
# @author: 李鹏飞
# """
# from __future__ import absolute_import
# from __future__ import unicode_literals
#
# import logging
# from urllib import urlencode
#
# import xlwt
# from django.conf import settings
# from django.contrib import messages
# from django.contrib.auth import REDIRECT_FIELD_NAME, login, logout
# from django.contrib.auth.hashers import make_password
# from django.contrib.auth.models import User, Group
# from django.contrib.auth.views import redirect_to_login
# from django.core.exceptions import ImproperlyConfigured
# from django.http import HttpResponse
# from django.shortcuts import render, redirect
# from django.utils.encoding import force_text, smart_str
#
# from enroll.libs.wechatpy.oauth import WeChatOAuth
# # from enroll.apps.tool.utils import check_mobile
# # from enroll.settings import conf
# from enroll.apps.common.generate import random_str
# from enroll.apps.wechat_api.wcommon import wxurllib2_request
# from enroll.settings import WECHAT_CONFIG
# from enroll.settings.config import DOMAIN_NAME
#
#
# class AccessMixin(object):
#     """
#     CBV mixin which verifies that the current user is authenticated.
#     """
#     """
#     Abstract CBV mixin that gives access mixins the same customizable
#     functionality.
#     """
#     login_url = None
#     permission_denied_message = ''
#     raise_exception = False
#     redirect_field_name = REDIRECT_FIELD_NAME
#
#     def get_login_url(self):
#         """
#         Override this method to override the login_url attribute.
#         """
#         login_url = self.login_url or settings.LOGIN_URL
#         if not login_url:
#             raise ImproperlyConfigured(
#                     '{0} is missing the login_url attribute. Define {0}.login_url, settings.LOGIN_URL, or override '
#                     '{0}.get_login_url().'.format(self.__class__.__name__)
#             )
#         return force_text(login_url)
#
#     def get_permission_denied_message(self):
#         """
#         Override this method to override the permission_denied_message attribute.
#         """
#         return self.permission_denied_message
#
#     def get_redirect_field_name(self):
#         """
#         Override this method to override the redirect_field_name attribute.
#         """
#         return self.redirect_field_name
#
#     def handle_no_permission(self):
#         if self.raise_exception:
#             notice = self.get_permission_denied_message()
#             return render(self.request, 'error.html', locals())
#         # messages.error(self.request, self.get_permission_denied_message())
#         #             return redirect(self.get_redirect_field_name())
#         #             raise PermissionDenied(self.get_permission_denied_message())
#         return redirect_to_login(self.request.get_full_path(), self.get_login_url(),
#                                  self.get_redirect_field_name())
#
#
# class LoginRequiredMixin(AccessMixin):
#     def dispatch(self, request, *args, **kwargs):
#         """没登陆或者是微信用户 跳转到登录页面"""
#         if not request.user.is_authenticated() or request.user.groups.filter(name=u'微信用户').count() > 0:
#             return redirect_to_login(self.request.get_full_path(), self.get_login_url(),
#                                      self.get_redirect_field_name())
#         # return self.handle_no_permission()
#         return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
#
#
# class WechatLoginRequiredMixin(AccessMixin):
#     def get_login_url(self):
#         """
#         Override this method to override the login_url attribute.
#         """
#         login_url = self.login_url or settings.MOBILE_URL
#         if not login_url:
#             raise ImproperlyConfigured(
#                     '{0} is missing the MOBILE_url attribute. Define {0}.login_url, settings.MOBILE_URL, or override '
#                     '{0}.get_login_url().'.format(self.__class__.__name__)
#             )
#         return force_text(login_url)
#
#     def dispatch(self, request, *args, **kwargs):
#         # TODO 还有问题
#         """没登陆或非微信用户 的跳转到登录页面"""
#         if not request.user.is_authenticated() or request.user.groups.filter(name=u'微信用户').count() == 0:
#             # return redirect_to_login(self.request.get_full_path(), self.get_login_url(),
#             #                          self.get_redirect_field_name())
#             return redirect(self.user_login())
#         # return self.handle_no_permission()
#         return super(WechatLoginRequiredMixin, self).dispatch(request, *args, **kwargs)
#
#     def get_openid(self):
#         """微信授权"""
#
#         logger.debug(u'接收到微信用户授权的第二步')
#         logger.debug(self.request.GET)
#
#         code = self.request.GET.get('code', '')
#         state = self.request.GET.get('state', '')
#         user = User()
#         # wechatuser = User()
#         logger.info(code)
#         if code:
#             data_list = [('appid', WECHAT_CONFIG['app_id']),
#                          ('code', code),
#                          ('grant_type', 'authorization_code'),
#                          ]
#             # 传统登录的
#             data_list.insert(1, ('secret', WECHAT_CONFIG['app_secret']))
#             url = 'https://api.weixin.qq.com/sns/oauth2/access_token?%s'
#             redict = wxurllib2_request(url % urlencode(data_list))
#             logger.debug(redict)
#             openid = redict.get('openid', '')
#             logger.error(openid)
#             # wechatuser = save_wechatuser(openid, wechatconfig)
#             # logger.debug(wechatuser)
#             # return wechat.fetch_access_token(code)
#             # 创建微信用户
#             try:
#                 user = User.objects.get(username=openid)
#             except Exception as e:
#                 password = make_password(random_str(6), None, 'pbkdf2_sha256')
#                 user = User.objects.create(username=openid, password=password)
#                 group = Group.objects.get(name="微信用户")
#                 user.groups.add(group)
#
#                 logger.info('%s创建成功' % openid)
#         else:
#             logger.error(u'接收到微信用户授权的第二步,参数不对[%s]' % self.request.GET)
#         return user
#
#     def user_login(self):
#         user = self.get_openid()
#         next_url = self.request.GET.get('next', '/activity/mobile/list/')
#         if user.id:
#             user.backend = 'django.contrib.auth.backends.ModelBackend'
#             login(self.request, user)
#             logger.info('%s创建成功' % user.username)
#             return next_url
#         else:
#             # # 保持登录用户和后端的连接
#             # user.backend = 'django.contrib.auth.backends.ModelBackend'
#             # login(self.request, user)
#             # # 记录该用户登录成功的日志
#             # logger.info('%s登录成功' % openid)
#             logger.error('登陆失败')
#             return self.mobile_oauth(self.request, next_url)
#
#     def mobile_oauth(self, request, next_url):
#         '''微信端跳转至授权 '''
#
#         # next_url = request.GET.get('next', '/user/mobile/index/')
#         # wechat = WechatConfig.objs.get_or_new()
#         domain_name = DOMAIN_NAME
#         logger.debug(next_url)
#         url = domain_name + next_url
#         logger.debug(url)
#         wechat = WeChatOAuth(WECHAT_CONFIG['app_id'], WECHAT_CONFIG['app_secret'],
#                              redirect_uri=url)
#         oauth2_url = wechat.authorize_url
#         logger.debug(oauth2_url)
#         logout(request)  # 退出登录之前的用户
#         return oauth2_url
#
#
# # class ManageMixin(LoginRequiredMixin):
# #     """admin和客服用,验证"""
# #     redirect_url = "user:login"
# #
# #     def handle_user(self):
# #         if not is_manage(self.request.user):
# #             messages.error(self.request, "您不是管理人员,无权进行操作")
# #             return False
# #         return True
# #
# #
# # class SuperUserMixin(LoginRequiredMixin):
# #     """admin,验证"""
# #     redirect_url = None
# #
# #     def handle_user(self):
# #         if not self.request.user.is_superuser:
# #             messages.error(self.request, "您不是超级管理员,无权进行操作")
# #             return False
# #         return True
# #
# #
# # def is_manage(user):
# #     """判断用户是admin,管理员的 返回true"""
# #     if user.is_superuser:
# #         return True
# #     group_list = user.groups.all()
# #     if group_list and group_list[0].name == conf.group_dict['manager']:
# #         return True
# #     else:
# #         return False
# #
# #
# # # 以下各个权限mixin,用于后台管理
# #
# #
# # class ViewUserMixin(PermissionRequiredMixin):
# #     """用户模块"""
# #     permission_required = ('user.view_user',)
# #     permission_denied_message = '你没有查看用户的权限'
# #
# #
# # class EditUserMixin(PermissionRequiredMixin):
# #     permission_required = ('user.edit_user',)
# #     permission_denied_message = '你没有操作用户的权限'
# #
# #
# # class ExportUserMixin(PermissionRequiredMixin):
# #     permission_required = ('user.export_user',)
# #     permission_denied_message = '你没有导出用户的权限'
# #
# #
# # class ViewOrderMixin(PermissionRequiredMixin):
# #     """交易模块"""
# #     permission_required = ('trade.view_order',)
# #     permission_denied_message = '你没有查看交易的权限'
# #
# #
# # class EditOrderMixin(PermissionRequiredMixin):
# #     permission_required = ('trade.edit_order',)
# #     permission_denied_message = '你没有操作交易的权限'
# #
# #
# # class ExportOrderMixin(PermissionRequiredMixin):
# #     permission_required = ('trade.export_order',)
# #     permission_denied_message = '你没有导出交易的权限'
# #
# #
# # class ViewHouseMixin(PermissionRequiredMixin):
# #     """房源模块"""
# #     permission_required = ('house.view_house',)
# #     permission_denied_message = '你没有查看房源的权限'
# #
# #
# # class EditHouseMixin(PermissionRequiredMixin):
# #     permission_required = ('house.edit_house',)
# #     permission_denied_message = '你没有操作房源的权限'
# #
# #
# # class ExportHouseMixin(PermissionRequiredMixin):
# #     permission_required = ('house.export_house',)
# #     permission_denied_message = '你没有导出房源的权限'
# #
# #
# # class ViewAdvertMixin(PermissionRequiredMixin):
# #     """广告模块"""
# #     permission_required = ('advert.view_advert',)
# #     permission_denied_message = '你没有查看广告的权限'
# #
# #
# # class EditAdvertMixin(PermissionRequiredMixin):
# #     permission_required = ('advert.edit_advert',)
# #     permission_denied_message = '你没有操作广告的权限'
# #
# #
# # class ExportAdvertMixin(PermissionRequiredMixin):
# #     permission_required = ('advert.export_advert',)
# #     permission_denied_message = '你没有导出广告的权限'
# #
# #
# # class EditHouseNewsMixin(PermissionRequiredMixin):
# #     permission_required = ('house_news.edit_house_news',)
# #     permission_denied_message = '你没有操作房屋咨询的权限'
# #
# #
# # class ViewHouseNewsMixin(PermissionRequiredMixin):
# #     permission_required = ('house_news.view_house_news',)
# #     permission_denied_message = '你没有查看房屋资讯的权限'
#
# # class EditStaffUserMixin(PermissionRequiredMixin):
# #     permission_required = ('user.add_staff_user',)
# #     permission_denied_message = '你没有操作员工用户的权限'
# #
# #
# # class ViewStaffUserMixin(PermissionRequiredMixin):
# #     permission_required = ('user.view_staff_user',)
# #     permission_denied_message = '你没有查看员工用户的权限'
#
#
# logger = logging.getLogger(__name__)
#
#
# # # CSV导出的Mixin 改为导出XLS文件
# class CSVMixin(object):
#     import sys
#     reload(sys)
#     sys.setdefaultencoding("utf-8")
#
#     # 修改
#     def _prepare_csv_data(self):
#         """
#         对get_queryset函数拿到的数据进行预处理,使其能够被get_csv_response函数使用
#         """
#         raw_data = self.csv_data()
#         if not raw_data:
#             return None
#         name = []
#         data = []
#         # 拿到中文名显示在第一行
#         for item in raw_data[0]:
#             if len(raw_data[0][item]) == 2:
#                 name.append(raw_data[0][item][1][0])
#         # 处理原始数据
#         for row in raw_data:
#             temp_list = []
#             for item in row:
#                 # 剔除不必要的项
#                 if len(row[item]) == 2:
#                     if item == 'GET_TIME':
#                         try:
#                             date = row[item][0].strftime("%Y-%m-%d %H:%M:%S".encode('utf-8')).decode('utf-8')
#                         except:
#                             date = row[item][0]
#                         temp_list.append('\t' + date)
#                     elif row[item][0] is None:
#                         temp_list.append('\t')
#                     else:
#                         temp_list.append('\t' + unicode(row[item][0]))
#             data.append(temp_list)
#         # 将name和data整合在一起形成如[[],[],[]]结构的数据
#         name = [name]
#         name.extend(data)
#         return name
#
#     def get_csv(self):
#         data_list = self._prepare_csv_data()
#         if not data_list:
#             messages.info(self.request, "无可导出数据")
#             raise ValueError
#         # 得到文件名称
#         return get_xls_response(data_list, self.csv_filename())
#
#     def get(self, request, *args, **kwargs):
#         if request.GET.get('csv'):
#             try:
#                 return self.get_csv()
#             except Exception as e:
#                 logger.info(e)
#                 messages.info(self.request, "XLS文件导出失败")
#                 return super(CSVMixin, self).get(request, *args, **kwargs)
#         else:
#             return super(CSVMixin, self).get(request, *args, **kwargs)
#
#     def csv_data(self):
#         return self.get_queryset()
#
#     def csv_filename(self):
#         """
#         返回csv文件名，根据需要导出csv的种类的不同，被不同的视图类重写
#         """
#         pass
#
#
# #
# #
# # class ConfigCSVMixin(CSVMixin):
# #     def _prepare_csv_data(self):
# #         """
# #         被所有继承的视图类重写，加入首行的名称
# #         :return:
# #         """
# #         content = []
# #         for row in self.csv_data():
# #             temp_list = []
# #             for item in row.values():
# #                 if item is None:
# #                     temp_list.append('\t')
# #                 elif isinstance(item, datetime.datetime):
# #                     temp_list.append('\t' + item.strftime('%Y-%m-%d %H:%M:%S'))
# #                 elif isinstance(item, datetime.time):
# #                     temp_list.append('\t' + item.strftime('%H:%M:%S'))
# #                 elif (item == 1 and len(temp_list) != 0) or item == '1':
# #                     temp_list.append('\t' + '是')
# #                 elif (item == 0 and len(temp_list) != 0) or item == '0':
# #                     temp_list.append('\t' + '否')
# #                 else:
# #                     temp_list.append('\t' + str(item))
# #             content.append(temp_list)
# #         return content
# #
# #
# # class Echo(object):
# #     def write(self, value):
# #         return value
# #
# #
# # class UnicodeWriter:
# #     """
# #     A CSV writer which will write rows to CSV file "f",
# #     which is encoded in the given encoding.
# #     """
# #
# #     def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# #         # Redirect output to a queue
# #         self.queue = cStringIO.StringIO()
# #         self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
# #         self.stream = f
# #         self.encoding = encoding
# #         self.encoder = codecs.getincrementalencoder(self.encoding)()
# #
# #     def writerow(self, row):
# #         #         self.writer.writerow([handle_column(s) for s in row])
# #         self.writer.writerow([s.encode(self.encoding) for s in row])
# #         # Fetch UTF-8 output from the queue ...
# #         data = self.queue.getvalue()
# #         data = data.decode(self.encoding)
# #         # ... and reencode it into the target encoding
# #         data = self.encoder.encode(data)
# #         # write to the target stream
# #         value = self.stream.write(data)
# #         # empty queue
# #         self.queue.truncate(0)
# #         return value
# #
# #     def writerows(self, rows):
# #         for row in rows:
# #             self.writerow(row)
# #
# #
# #
# def get_xls_response(data_list, filename):
#     """
#     生成xls文件
#     :param data_list: 文件数据 [[],[]]
#     :param filename: 文件名
#     :param encoding: 文字编码类型
#     """
#     # 占用内存会有点多，以后需要优化
#     wb = xlwt.Workbook(encoding='utf-8')
#     ws = wb.add_sheet('Sheet1')
#     for row_num in range(len(data_list)):
#         for col_num in range(len(data_list[row_num])):
#             ws.write(row_num, col_num, data_list[row_num][col_num])
#     response = HttpResponse(content_type="application/vnd.ms-excel")
#     response['Content-Disposition'] = 'attachment;filename=%s' % smart_str(filename + '.xls')
#     print response['Content-Disposition']
#     wb.save(response)
#     return response
